import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import datamodel
from links import Links

class Schools(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        
        links = Links().get()

        if user:
            user_msg = ('Hello %s <a href="%s">Sign out</a><br>Is administrator: %s' % 
                (user.nickname(), users.create_logout_url("/"), users.is_current_user_admin()))
            
            q = datamodel.School.all()
            q.order("schName")
            
            if q.count() > 0:
                schResults = q.fetch(10)
                
                schTable = '<table>'
                for sch in schResults:
                    schTable += ('<tr><td>%s</td><td>%s</td></tr>' %
                                 (sch.schName, sch.webUrl))
                schTable += '</table>'
            else:
                schTable = '<p>No schools found</p>'
            
        else:
            user_msg = ('<a href="%s">Sign In</a>' % 
                (users.create_login_url(self.request.uri)))
            
        template_values = {
                           'links': links,
                           'user_msg': user_msg,
                           'schTable': schTable
                           }
        
        path = os.path.join(os.path.dirname(__file__), 'admin.html')
        self.response.out.write(template.render(path, template_values))